﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;

using System.Diagnostics;

using System.Security.Permissions;
using Microsoft.SharePoint.Security;
using Microsoft.Office.Server.ActivityFeed;
using System.Security.Principal;
using Microsoft.Office.Server.UserProfiles;
using System.Net;
using Microsoft.SharePoint.Utilities;
using System.Web;


namespace eGov.SharePoint.MyPeeps.Layouts.eGov
{
    public partial class MyPeepsRedirect : LayoutsPageBase
    {
        public bool _error = false;
        private string _pageurl = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToMyPeeps();
        }

        private void RedirectToMyPeeps()
        {
            string currentLoggedUser = string.Empty;

            SPSite siteColl = null;
            SPWeb site = null;

            siteColl = SPContext.Current.Site;
            site = SPContext.Current.Web;

            string webAppUrl = siteColl.ServerRelativeUrl;
            Debug.WriteLine("Web App URL = {0}", webAppUrl);

            try
            {
                SPUser currentuser = site.CurrentUser;
                if (currentuser != null)
                    currentLoggedUser = currentuser.LoginName;

                string[] splittedAccountName = null;

                if (currentuser != null)
                    splittedAccountName = currentLoggedUser.Split('\\');

                string userAcc = string.Empty;

                //Split the acount CONTOSO\user
                if (splittedAccountName != null && splittedAccountName.Length > 1)
                    userAcc = splittedAccountName[1];
                if (userAcc.Length == 0)
                {
                    //User does not have a domain
                    userAcc = currentuser.LoginName;
                }
                UserProfileManager profileManager = new UserProfileManager(SPServiceContext.GetContext(SPContext.Current.Site));
            
                string userWebUrl = String.Format("/" + profileManager.PersonalSiteInclusion + "/{0}", userAcc.Replace(".", "_"));
                //_pageurl = SPContext.Current.Site.WebApplication.Sites["/"].Url + userWebUrl + "/MyPeeps.aspx"; 
                _pageurl = "http://" + HttpContext.Current.Request.Url.Authority + userWebUrl + "/MyPeeps.aspx";
                bool isValidUrl = true;
                if (SPUtility.RedirectValidate(_pageurl, HttpContext.Current))
                {
                    //The following is imoplkemented to resolve redirection inconsistencies on multiple zone urls
                    //Double Check for Additional zone URLs
                    string pageUrl = SPContext.Current.Site.WebApplication.Sites["/"].Url + userWebUrl + "/MyPeeps.aspx";
                    SPSiteCollection sites = SPContext.Current.Site.WebApplication.Sites;
                    try
                    {
                        using (SPWeb myWeb = sites[userWebUrl].OpenWeb())
                        {
                            if (myWeb == null || !myWeb.Exists)
                                isValidUrl = false;
                            string relativePageUrl = "Mypeeps.aspx";
                            if (!SPUtility.RedirectValidate(relativePageUrl, myWeb))
                                isValidUrl = false;
                        }
                    }
                    catch (Exception)
                    {
                        isValidUrl = false;
                    }


                    if(isValidUrl)
                        SPUtility.Redirect(_pageurl, SPRedirectFlags.Trusted, HttpContext.Current);

                    //if (SPUtility.RedirectValidate(pageUrl, HttpContext.Current))
                    //    SPUtility.Redirect(_pageurl, SPRedirectFlags.Trusted, HttpContext.Current);
                }
                else
                {
                    //Do nothing, just display the current page with the error message that the user's mysite is noty created.
                }
            }
            catch (Exception exp)
            {
                Debug.WriteLine(exp.ToString());
            }
        }

    }
}
//bool myPeepsPageUrlExists = true;
//         bool myPeepsPagHttpCopntextUrlExists = true;
//         bool myPeepsPagSPCopntextUrlExists = true;
//         string pageurlHttpContext  = "http://" + HttpContext.Current.Request.Url.Authority + userWebUrl + "/MyPeeps.aspx";               
//         if (!SPUtility.RedirectValidate(pageurlHttpContext, HttpContext.Current))
//         {
//            myPeepsPageUrlExists = false;
//         }

//         string pageUrlSPContext = SPContext.Current.Site.WebApplication.Sites["/"].Url + userWebUrl + "/MyPeeps.aspx";
//         if (SPUtility.RedirectValidate(pageUrlSPContext, HttpContext.Current))
//         {
//             myPeepsPageUrlExists = false;
//         }


//         if (myPeepsPageUrlExists)
//         {
//             SPUtility.Redirect(_pageurl, SPRedirectFlags.Trusted, HttpContext.Current);
//         }
